const pool = require('../config/db');

/**
 * @desc    获取学生性别分布统计（饼图）
 * @route   GET /api/stats/gender-distribution
 * @access  Private
 */
const getGenderDistribution = async (req, res) => {
    try {
    const [result] = await pool.query(`
        SELECT 
        gender, 
        COUNT(*) as count,
        (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM students)) as percentage
        FROM students
        GROUP BY gender
    `);

    res.json({
        labels: result.map(item => item.gender),
        data: result.map(item => item.count),
        percentages: result.map(item => parseFloat(item.percentage.toFixed(2))),
        total: result.reduce((sum, item) => sum + item.count, 0)
    });
    } catch (error) {
    console.error('获取性别分布统计错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

/**
 * @desc    获取学生身高统计（折线图）
 * @route   GET /api/stats/height
 * @access  Private
 */
const getHeightStats = async (req, res) => {
    try {
    // 获取所有学生的身高并排序
    const [result] = await pool.query(
        'SELECT height FROM students WHERE height IS NOT NULL ORDER BY height'
    );

    // 提取身高数据
    const heights = result.map(item => parseFloat(item.height));
    
    // 按身高区间分组统计
    const minHeight = Math.floor(Math.min(...heights) || 150);
    const maxHeight = Math.ceil(Math.max(...heights) || 190);
    const interval = 5; // 每5厘米一个区间
    
    const labels = [];
    const data = [];
    
    for (let h = minHeight; h <= maxHeight; h += interval) {
        const nextH = h + interval;
        labels.push(`${h}-${nextH}cm`);
        
        // 统计该区间的学生数量
        const count = heights.filter(height => height >= h && height < nextH).length;
        data.push(count);
    }

    res.json({
        labels,
        data,
        average: heights.length > 0 
        ? parseFloat((heights.reduce((sum, h) => sum + h, 0) / heights.length).toFixed(2))
        : 0
    });
    } catch (error) {
    console.error('获取身高统计错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

/**
 * @desc    获取学生体重统计（柱状图）
 * @route   GET /api/stats/weight
 * @access  Private
 */
const getWeightStats = async (req, res) => {
    try {
    // 获取所有学生的体重
    const [result] = await pool.query(
        'SELECT weight FROM students WHERE weight IS NOT NULL'
    );

    // 提取体重数据
    const weights = result.map(item => parseFloat(item.weight));
    
    // 按5公斤为区间分组统计
    if (weights.length > 0) {
        const minWeight = Math.floor(Math.min(...weights));
        const maxWeight = Math.ceil(Math.max(...weights));
        
        // 确保区间从能被5整除的数开始
        const startWeight = Math.floor(minWeight / 5) * 5;
        const endWeight = Math.ceil(maxWeight / 5) * 5;
        
        const labels = [];
        const data = [];
        
        for (let w = startWeight; w < endWeight; w += 5) {
        const nextW = w + 5;
        labels.push(`${w}-${nextW}kg`);
        
        // 统计该区间的学生数量
        const count = weights.filter(weight => weight >= w && weight < nextW).length;
        data.push(count);
        }

        res.json({
        labels,
        data,
        average: parseFloat((weights.reduce((sum, w) => sum + w, 0) / weights.length).toFixed(2))
        });
    } else {
        res.json({
        labels: [],
        data: [],
        average: 0
        });
    }
    } catch (error) {
    console.error('获取体重统计错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

module.exports = {
    getGenderDistribution,
    getHeightStats,
    getWeightStats
};

